package com.hq.fxh.No0_ChengQu.Login;

import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hq.fxh.CustomerView.TimeCount;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Intefers.NetworkSubscriber;
import com.hq.fxh.Modle.ForgetPwdRes;
import com.hq.fxh.No0_ChengQu.Activity.BaseActivity;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.item.RefreshMvpView;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Activity.item.ToastUtils;
import com.hq.fxh.No3_TuiGuang.MyMoBan.ClearableEidtText;
import com.hq.fxh.No3_TuiGuang.MyMoBan.Model.CommonRes;
import com.hq.fxh.R;
import com.hq.fxh.Utils.CheckUtils;
import com.hq.fxh.Utils.IntentUtils;
import com.hq.fxh.Utils.Tool;

import java.io.UnsupportedEncodingException;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;

/**
 * @author 大圣
 * @ClassName FindPwdActivity
 * @Description :
 * @Created 16/5/20
 * @Email qwqe601660957@163.com
 */
public class FindPwdActivity extends BaseActivity implements View.OnClickListener {
    protected ImageView toolbarImageBack;
    protected LinearLayout toolbarLayoutBack;
    protected TextView toolBarTvTitle;
    protected LinearLayout toolbarContent;
    protected TextView tvRegisterAgreement;
    protected LinearLayout resetLayoutContent;
    protected ImageView imageFindpsPhone;
    protected ImageView imageFindpsCode;
    protected ImageView imageFindpsPassword;
    /**
     * 输入手机号码
     */
    private ClearableEidtText etPhoneNumber;
    /**
     * 获取手机验证码
     */
    private TextView tvGetCheckCode;
    /**
     * 输入手机验证码
     */
    private ClearableEidtText etCheckCode;
    /**
     * 输入新密码
     */
    private ClearableEidtText etNewPassword;
    /**
     * 确定新密码
     */
    /**
     * 完成按钮
     */
    private Button btnNext;
    /**
     * 获取验证码后倒计时
     */
    private TimeCount timeCount;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_findpsw;
    }

    @Override
    protected void initView() {
        setSysColor(R.color.red, true);
        etPhoneNumber = (ClearableEidtText) findViewById(R.id.etPhoneNumber);
        tvGetCheckCode = (TextView) findViewById(R.id.tvGetCheckCode);
        etCheckCode = (ClearableEidtText) findViewById(R.id.etCheckCode);
        etNewPassword = (ClearableEidtText) findViewById(R.id.etNewPassword);
        btnNext = (Button) findViewById(R.id.btnNext);
        toolbarImageBack = (ImageView) findViewById(R.id.toolbar_image_back);
        toolbarLayoutBack = (LinearLayout) findViewById(R.id.toolbar_Layout_back);
        toolbarLayoutBack.setOnClickListener(FindPwdActivity.this);
        toolBarTvTitle = (TextView) findViewById(R.id.toolBar_tv_Title);
        toolbarContent = (LinearLayout) findViewById(R.id.toolbar_Content);
        tvRegisterAgreement = (TextView) findViewById(R.id.tvRegisterAgreement);
        resetLayoutContent = (LinearLayout) findViewById(R.id.reset_layout_Content);
        imageFindpsPhone = (ImageView) findViewById(R.id.image_findps_phone);
        imageFindpsCode = (ImageView) findViewById(R.id.image_findps_Code);
        imageFindpsPassword = (ImageView) findViewById(R.id.image_findps_Password);
    }

    @Override
    protected void initData() {
        toolBarTvTitle.setText("找回密码");

        timeCount = new TimeCount(60 * 1000, 1000, tvGetCheckCode);
        etNewPassword.setFilters(new InputFilter[]{
                new InputFilter.LengthFilter(20),
                new InputFilter() {

                    @Override
                    public CharSequence filter(CharSequence source, int start,
                                               int end, Spanned dest, int dstart, int dend) {

                        if (isCN(source.toString())) {
                            if (dstart >= 0) {
                                etNewPassword.setSelection(dstart);
                                return "";
                            } else {
                                if (source.length() + dest.length() > 0) {
                                    return source.subSequence(start, start + 0 - dest.length());
                                } else {
                                    return source;
                                }
                            }
                        } else {
                            return source;
                        }
                    }
                }
        });

        registerListener();
        Tool.setEditorChange(etNewPassword, imageFindpsPassword, R.mipmap.dl_mima, R.mipmap.dl_mima_to);
        Tool.setEditorChange(etPhoneNumber, imageFindpsPhone, R.mipmap.dl_shouji, R.mipmap.dl_shouji_to);
        Tool.setEditorChange(etCheckCode, imageFindpsCode, R.mipmap.dl_yanzheng, R.mipmap.dl_yanzheng_to);

    }

    @Override
    protected void onResume() {
        super.onResume();
        JAnalyticsInterface.onPageStart(this, "找回密码");
    }

    @Override
    protected void onPause() {
        super.onPause();
        JAnalyticsInterface.onPageEnd(this, "找回密码");
    }


    public boolean isCN(String str) {
        try {
            byte[] bytes = str.getBytes("UTF-8");
            if (bytes.length == str.length()) {
                return false;
            } else {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    private void registerListener() {
        tvGetCheckCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getCheckCode();
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rePassword();
            }
        });
        etCheckCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                checkCode = editable.toString();
//                checkInputFull();
            }
        });
        etPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                phoneNumber = editable.toString();
//                checkInputFull();
            }
        });

        etNewPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                newPassword = editable.toString();
//                checkInputFull();
            }
        });

    }

    private String checkCode;
    private String phoneNumber;
    private String password;
    private String newPassword;
    /**
     * 输入检查
     */

    /**
     * 修改密码
     */
    private void rePassword() {
        String phoneNum = CheckUtils.checkEditText(etPhoneNumber);
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtils.show(this, "手机号不能为空");
            return;
        }
        if (!CheckUtils.isMobileNumber(phoneNum)) {
            ToastUtils.show(this, "输入的手机号有误");
            return;
        }
        String code = CheckUtils.checkEditText(etCheckCode);
        if (TextUtils.isEmpty(code)) {
            ToastUtils.show(this, "验证码不能为空");
            return;
        }
        final String password = CheckUtils.checkEditText(etNewPassword);
        if (TextUtils.isEmpty(password)) {
            ToastUtils.show(this, "密码不能为空");
            return;
        } else if (password.length() < 6) {
            ToastUtils.show(this, "密码不能小于6位");
            return;
        }
/**
 * 忘记密码
 */
        UserServiceImpl.updateByMemberPasswordWhenForget(phoneNum, password, code, new NetworkSubscriber<ForgetPwdRes>() {
            @Override
            public int onSuccess(ForgetPwdRes data) {
                super.onSuccess(data);
                if (data != null && data.getCode() == 0) {
                    ToastUtils.show(FindPwdActivity.this, "修改密码成功");
//                    SharedPreferenceUtils.setPwd(FindPwdActivity.this,password);
                    IntentUtils.openActivity(FindPwdActivity.this, LoginActivity.class);
                    finish();
                } else {
                    ToastUtils.show(FindPwdActivity.this, data.getMsg());
                }
                return 0;
            }
        });
    }


    private String phoneNum;

    /**
     * 修改密码获取验证码
     */
    private void getCheckCode() {
        phoneNum = checkPhone();
        if (TextUtils.isEmpty(phoneNum)) {
            return;
        }
/**
 * 忘记密码验证码
 */
        UserServiceImpl.sendMsg(phoneNum, 2, new NetworkSubscriber<CommonRes>() {
            @Override
            public int onSuccess(CommonRes data) {
                super.onSuccess(data);
                if (data != null && data.getCode() == 0) {
                    timeCount.start();
                } else {
                    ToastUtils.show(FindPwdActivity.this, data.getMsg());
                }
                return 0;
            }
        });
    }

    public String checkPhone() {
        String phoneNum = CheckUtils.checkEditText(etPhoneNumber);
        if (TextUtils.isEmpty(phoneNum)) {
            ToastUtils.show(this, "请输入手机号");
            return "";
        }
        if (!CheckUtils.isMobileNumber(phoneNum)) {
            ToastUtils.show(this, "输入的手机号有误");
            return "";
        }
        return phoneNum;
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.toolbar_Layout_back) {
            finish();
        }
    }

    private class CheckCodeView implements RefreshMvpView<String> {

        @Override
        public void onRefreshStart() {
            showProgressDialog("");
        }

        @Override
        public void onRefreshEnd() {
            dissProgressDialoig();
        }

        @Override
        public void onError(String errorCode, String errorMsg) {
            ToastUtils.show(FindPwdActivity.this, errorMsg);
        }

        @Override
        public void fetchData(String result) {

        }
    }

    private class ResetPasswordView implements RefreshMvpView<String> {

        @Override
        public void onRefreshStart() {
            showProgressDialog("");
        }

        @Override
        public void onRefreshEnd() {
            dissProgressDialoig();
        }

        @Override
        public void onError(String errorCode, String errorMsg) {
            ToastUtils.show(FindPwdActivity.this, errorMsg);
        }

        @Override
        public void fetchData(String result) {
            ToastUtils.show(FindPwdActivity.this, "密码重置成功");
            finish();
        }
    }


}
